package com.course.servlet;

import com.course.entity.Teacher;
import com.course.service.CourseService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/laoshi_delete_course")
public class LaoshiDeleteCourseServlet extends HttpServlet {
    private final CourseService courseService = new CourseService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        HttpSession session = request.getSession(false); // Do not create a new session if one doesn't exist
        Teacher teacher = null;

        if (session != null) {
            teacher = (Teacher) session.getAttribute("teacher");
        }

        if (teacher == null) {
            response.sendRedirect(request.getContextPath() + "/laoshi_login.jsp");
            return;
        }

        String courseIdStr = request.getParameter("courseId");
        if (courseIdStr != null && !courseIdStr.isEmpty()) {
            try {
                int courseId = Integer.parseInt(courseIdStr);
                boolean success = courseService.deleteCourse(courseId);

                if (success) {
                    request.getSession().setAttribute("successMessage", "课程删除成功！");
                } else {
                    request.getSession().setAttribute("errorMessage", "课程删除失败，请稍后重试。");
                }
            } catch (NumberFormatException e) {
                request.getSession().setAttribute("errorMessage", "无效的课程ID。");
                e.printStackTrace();
            }
        } else {
            request.getSession().setAttribute("errorMessage", "课程ID不能为空。");
        }

        response.sendRedirect(request.getContextPath() + "/laoshi_my_courses");
    }
} 